"""
摄像头业务服务层
Enhanced camera service with comprehensive business validation, error handling,
and integration with advanced repository features for camera data persistence.
"""
import asyncio
import httpx
import re
from typing import List, Optional, Dict, Any, Tuple
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from repositories.camera_repository import (
    CameraRepository, CameraRepositoryError, 
    CameraNotFoundError, CameraDuplicateError
)
from repositories.crud_operations import EnhancedCameraRepository
from repositories.advanced_queries import AdvancedCameraQueries, LocationBounds
from schemas.camera import (
    CameraCreate, CameraUpdate, CameraFilters, CameraStatus,
    CameraConnectionTest, CameraResponse, CameraListResponse
)
from models.camera import Camera
from core.config_manager import get_config_manager, CameraAIConfig
from core.crud_error_handler import (
    CRUDError, ValidationError as CRUDValidationError, DuplicateError, 
    NotFoundError, crud_error_handler
)
from core.exceptions import (
    CameraError, CameraNotFoundError as NewCameraNotFoundError, 
    CameraDuplicateError as NewCameraDuplicateError,
    CameraValidationError, CameraConnectionError, CameraDependencyError,
    ValidationError, BusinessRuleError, ErrorCollector, ErrorCode
)
from services.validation.camera_validator_simple import (
    CameraValidator, ValidationSummary, ValidationSeverity
)
from services.monitoring.camera_statistics import CameraStatisticsService
import structlog

logger = structlog.get_logger(__name__)


class CameraServiceError(Exception):
    """摄像头服务异常基类"""
    pass


class CameraValidationError(CameraServiceError):
    """摄像头验证错误"""
    pass


class CameraBusinessError(CameraServiceError):
    """摄像头业务逻辑错误"""
    pass


class CameraService:
    """
    摄像头业务服务类
    Enhanced service with comprehensive business validation, error handling,
    and integration with advanced repository features.
    """
    
    def __init__(self, db: Session):
        self.db = db
        self.repository = CameraRepository(db)
        self.enhanced_repository = EnhancedCameraRepository(db)
        self.advanced_queries = AdvancedCameraQueries(db)
        self.config_manager = get_config_manager()
        self.validator = CameraValidator(self.repository, self.advanced_queries)  # 添加增强验证器
        self.statistics_service = CameraStatisticsService(db)  # 添加统计监控服务
        
        # 业务规则配置
        self.max_cameras_per_location = 50
        self.min_camera_distance_meters = 10.0
        self.allowed_rtsp_ports = [554, 8554, 1935]
        self.coordinate_precision = 6  # 小数点后位数
    
    @crud_error_handler("create_camera")
    async def create_camera(self, camera_data: CameraCreate, validate_connection: bool = True) -> Camera:
        """
        创建摄像头 - 包含完整的业务验证逻辑
        
        Args:
            camera_data: 摄像头创建数据
            validate_connection: 是否验证连接
            
        Returns:
            Camera: 创建的摄像头对象
            
        Raises:
            CameraValidationError: 验证失败
            CameraDuplicateError: 名称重复
            CameraBusinessError: 业务规则违反
        """
        try:
            # 1. 使用增强验证器进行全面验证
            validation_summary = self.validator.validate_create(camera_data)
            
            # 2. 检查验证结果
            if not validation_summary.valid:
                error_messages = ValidationHelper.format_validation_messages(validation_summary)
                raise CameraValidationError(f"摄像头数据验证失败:\n" + "\n".join(error_messages))
            
            # 3. 记录验证警告（如果有）
            if validation_summary.warnings:
                warning_messages = [f"[WARNING] {w.field}: {w.message}" for w in validation_summary.warnings]
                logger.warning("摄像头创建验证警告", 
                             name=camera_data.name, 
                             warnings=warning_messages)
            
            # 4. 连接测试（可选）
            connection_test = None
            if validate_connection and camera_data.rtsp_url:
                connection_test = await self.test_rtsp_connection(camera_data.rtsp_url)
                if not connection_test.success:
                    logger.warning(
                        "RTSP连接测试失败，但仍创建摄像头",
                        rtsp_url=camera_data.rtsp_url,
                        error=connection_test.message
                    )
            
            # 5. 创建摄像头
            camera = self.enhanced_repository.create_with_validation(camera_data)
            
            # 6. 根据连接测试结果更新状态
            if connection_test and connection_test.success:
                camera = self.repository.update_status(camera.id, CameraStatus.ONLINE)
            
            # 7. 记录创建日志
            logger.info("摄像头创建成功",
                       camera_id=camera.id,
                       name=camera.name,
                       location=camera.location,
                       validation_time=validation_summary.validation_time,
                       validation_checks=validation_summary.total_checks,
                       connection_tested=validate_connection,
                       connection_success=connection_test.success if connection_test else None)
            
            return camera
            
        except (CameraRepositoryError, CRUDError) as e:
            logger.error("摄像头创建失败", name=camera_data.name, error=str(e))
            raise CameraBusinessError(f"创建摄像头失败: {str(e)}") from e
        except Exception as e:
            logger.error("摄像头创建异常", name=camera_data.name, error=str(e))
            raise CameraServiceError(f"创建摄像头异常: {str(e)}") from e
    
    async def _validate_camera_data(self, camera_data: CameraCreate) -> None:
        """验证摄像头数据"""
        errors = []
        
        # 名称验证
        if not camera_data.name or len(camera_data.name.strip()) == 0:
            errors.append("摄像头名称不能为空")
        elif len(camera_data.name) > 255:
            errors.append("摄像头名称长度不能超过255个字符")
        elif not re.match(r'^[\u4e00-\u9fa5a-zA-Z0-9\-_\s]+$', camera_data.name):
            errors.append("摄像头名称只能包含中文、英文、数字、连字符和下划线")
        
        # 坐标验证
        if not (-180 <= camera_data.longitude <= 180):
            errors.append("经度必须在-180到180之间")
        if not (-90 <= camera_data.latitude <= 90):
            errors.append("纬度必须在-90到90之间")
        
        # 坐标精度验证
        lng_str = str(camera_data.longitude)
        lat_str = str(camera_data.latitude)
        if '.' in lng_str and len(lng_str.split('.')[1]) > self.coordinate_precision:
            errors.append(f"经度精度不能超过{self.coordinate_precision}位小数")
        if '.' in lat_str and len(lat_str.split('.')[1]) > self.coordinate_precision:
            errors.append(f"纬度精度不能超过{self.coordinate_precision}位小数")
        
        # 高度验证
        if camera_data.height is not None and camera_data.height < 0:
            errors.append("摄像头高度不能为负数")
        
        # RTSP URL验证
        if camera_data.rtsp_url:
            if not camera_data.rtsp_url.startswith('rtsp://'):
                errors.append("RTSP地址必须以rtsp://开头")
            else:
                # 验证RTSP URL格式和端口
                rtsp_pattern = r'rtsp://(?:[^:]+:[^@]+@)?[^:/]+(?::(\d+))?/.*'
                match = re.match(rtsp_pattern, camera_data.rtsp_url)
                if not match:
                    errors.append("RTSP地址格式不正确")
                elif match.group(1):  # 有端口号
                    port = int(match.group(1))
                    if port not in self.allowed_rtsp_ports:
                        errors.append(f"RTSP端口必须是{self.allowed_rtsp_ports}中的一个")
        
        # WVP设备ID验证
        if camera_data.wvp_device_id:
            if not re.match(r'^\d{20}$', camera_data.wvp_device_id):
                errors.append("WVP设备ID必须是20位数字")
        
        if camera_data.wvp_channel_id:
            if not re.match(r'^\d{20}$', camera_data.wvp_channel_id):
                errors.append("WVP通道ID必须是20位数字")
        
        # 处理帧率验证
        if camera_data.processing_fps < 1 or camera_data.processing_fps > 30:
            errors.append("处理帧率必须在1-30之间")
        
        # 优先级验证
        if camera_data.priority_level < 1 or camera_data.priority_level > 10:
            errors.append("优先级必须在1-10之间")
        
        if errors:
            raise CameraValidationError(f"数据验证失败: {'; '.join(errors)}")
    
    async def _validate_business_rules(self, camera_data: CameraCreate) -> None:
        """验证业务规则"""
        errors = []
        
        # 1. 检查名称唯一性
        if self.repository.exists_by_name(camera_data.name):
            errors.append(f"摄像头名称 '{camera_data.name}' 已存在")
        
        # 2. 检查WVP设备唯一性
        if camera_data.wvp_device_id and camera_data.wvp_channel_id:
            existing_wvp = self.repository.get_by_wvp_device(
                camera_data.wvp_device_id, 
                camera_data.wvp_channel_id
            )
            if existing_wvp:
                errors.append(f"WVP设备 {camera_data.wvp_device_id}:{camera_data.wvp_channel_id} 已存在")
        
        # 3. 检查位置摄像头数量限制
        if camera_data.location:
            location_cameras = self.repository.get_cameras_by_location(camera_data.location, exact_match=True)
            if len(location_cameras) >= self.max_cameras_per_location:
                errors.append(f"位置 '{camera_data.location}' 的摄像头数量已达到上限({self.max_cameras_per_location})")
        
        # 4. 检查摄像头间距离
        nearby_cameras = self.advanced_queries.get_cameras_in_radius(
            camera_data.longitude,
            camera_data.latitude,
            self.min_camera_distance_meters / 1000  # 转换为公里
        )
        if nearby_cameras:
            errors.append(f"距离{self.min_camera_distance_meters}米内已有其他摄像头")
        
        if errors:
            raise CameraBusinessError(f"业务规则验证失败: {'; '.join(errors)}")
    
    def get_camera(self, camera_id: int, include_relations: bool = False) -> Optional[Camera]:
        """
        获取摄像头详情
        
        Args:
            camera_id: 摄像头ID
            include_relations: 是否包含关联数据
            
        Returns:
            Optional[Camera]: 摄像头对象或None
        """
        try:
            return self.repository.get_by_id(camera_id, include_relations)
        except Exception as e:
            logger.error("获取摄像头详情失败", camera_id=camera_id, error=str(e))
            return None
    
    def get_camera_list(
        self, 
        filters: CameraFilters,
        sort_by: str = "created_at",
        sort_order: str = "desc",
        include_relations: bool = False
    ) -> CameraListResponse:
        """
        获取摄像头列表 - 支持高级筛选和排序
        
        Args:
            filters: 筛选条件
            sort_by: 排序字段
            sort_order: 排序方向
            include_relations: 是否包含关联数据
            
        Returns:
            CameraListResponse: 摄像头列表响应
        """
        try:
            cameras, total = self.repository.get_list(
                filters, sort_by, sort_order, include_relations
            )
            
            # 计算分页信息
            pages = (total + filters.size - 1) // filters.size
            
            # 转换为响应格式
            camera_responses = []
            for camera in cameras:
                try:
                    camera_response = CameraResponse.model_validate(camera)
                    camera_responses.append(camera_response)
                except Exception as e:
                    logger.warning("摄像头数据转换失败", camera_id=camera.id, error=str(e))
                    continue
            
            return CameraListResponse(
                items=camera_responses,
                total=total,
                page=filters.page,
                size=filters.size,
                pages=pages,
                has_previous=filters.page > 1,
                has_next=filters.page < pages,
                filtered_count=total  # 目前没有额外筛选，所以等于总数
            )
            
        except Exception as e:
            logger.error("获取摄像头列表失败", error=str(e))
            # 返回空列表而不是抛出异常
            return CameraListResponse(
                items=[],
                total=0,
                page=filters.page,
                size=filters.size,
                pages=0,
                has_previous=False,
                has_next=False,
                filtered_count=0
            )
    
    @crud_error_handler("update_camera")
    async def update_camera(
        self, 
        camera_id: int, 
        camera_data: CameraUpdate,
        validate_connection: bool = False
    ) -> Optional[Camera]:
        """
        更新摄像头 - 包含业务验证和冲突检查
        
        Args:
            camera_id: 摄像头ID
            camera_data: 更新数据
            validate_connection: 是否验证连接
            
        Returns:
            Optional[Camera]: 更新后的摄像头对象
            
        Raises:
            CameraNotFoundError: 摄像头不存在
            CameraValidationError: 验证失败
            CameraBusinessError: 业务规则违反
        """
        try:
            # 1. 检查摄像头是否存在
            existing_camera = self.repository.get_by_id(camera_id)
            if not existing_camera:
                raise CameraNotFoundError(f"摄像头 ID {camera_id} 不存在")
            
            # 2. 使用增强验证器验证更新数据
            validation_summary = self.validator.validate_update(camera_id, camera_data)
            
            # 3. 检查验证结果
            if not validation_summary.valid:
                error_messages = ValidationHelper.format_validation_messages(validation_summary)
                raise CameraValidationError(f"摄像头更新数据验证失败:\n" + "\n".join(error_messages))
            
            # 4. 记录验证警告（如果有）
            if validation_summary.warnings:
                warning_messages = [f"[WARNING] {w.field}: {w.message}" for w in validation_summary.warnings]
                logger.warning("摄像头更新验证警告", 
                             camera_id=camera_id, 
                             warnings=warning_messages)
            
            # 5. 连接测试（可选）
            if (validate_connection and 
                camera_data.rtsp_url and 
                camera_data.rtsp_url != existing_camera.rtsp_url):
                
                connection_test = await self.test_rtsp_connection(camera_data.rtsp_url)
                if not connection_test.success:
                    logger.warning(
                        "新RTSP地址连接测试失败",
                        camera_id=camera_id,
                        rtsp_url=camera_data.rtsp_url,
                        error=connection_test.message
                    )
            
            # 6. 执行更新
            updated_camera = self.enhanced_repository.update_with_validation(camera_id, camera_data)
            
            # 7. 记录更新日志
            logger.info("摄像头更新成功",
                       camera_id=camera_id,
                       name=updated_camera.name,
                       validation_time=validation_summary.validation_time,
                       validation_checks=validation_summary.total_checks,
                       updated_fields=list(camera_data.model_dump(exclude_unset=True).keys()))
            
            return updated_camera
            
        except (CameraRepositoryError, CRUDError) as e:
            logger.error("摄像头更新失败", camera_id=camera_id, error=str(e))
            raise CameraBusinessError(f"更新摄像头失败: {str(e)}") from e
        except Exception as e:
            logger.error("摄像头更新异常", camera_id=camera_id, error=str(e))
            raise CameraServiceError(f"更新摄像头异常: {str(e)}") from e
    
    async def _validate_update_data(
        self, 
        camera_id: int, 
        camera_data: CameraUpdate, 
        existing_camera: Camera
    ) -> None:
        """验证更新数据"""
        errors = []
        
        # 名称验证
        if camera_data.name is not None:
            if not camera_data.name or len(camera_data.name.strip()) == 0:
                errors.append("摄像头名称不能为空")
            elif len(camera_data.name) > 255:
                errors.append("摄像头名称长度不能超过255个字符")
            elif camera_data.name != existing_camera.name:
                # 检查名称冲突
                if self.repository.exists_by_name(camera_data.name, exclude_id=camera_id):
                    errors.append(f"摄像头名称 '{camera_data.name}' 已存在")
        
        # 坐标验证
        if camera_data.longitude is not None:
            if not (-180 <= camera_data.longitude <= 180):
                errors.append("经度必须在-180到180之间")
        
        if camera_data.latitude is not None:
            if not (-90 <= camera_data.latitude <= 90):
                errors.append("纬度必须在-90到90之间")
        
        # RTSP URL验证
        if camera_data.rtsp_url is not None:
            if camera_data.rtsp_url and not camera_data.rtsp_url.startswith('rtsp://'):
                errors.append("RTSP地址必须以rtsp://开头")
        
        # WVP设备验证
        new_device_id = camera_data.wvp_device_id or existing_camera.wvp_device_id
        new_channel_id = camera_data.wvp_channel_id or existing_camera.wvp_channel_id
        
        if (new_device_id and new_channel_id and 
            (camera_data.wvp_device_id is not None or camera_data.wvp_channel_id is not None)):
            
            existing_wvp = self.repository.get_by_wvp_device(new_device_id, new_channel_id)
            if existing_wvp and existing_wvp.id != camera_id:
                errors.append(f"WVP设备 {new_device_id}:{new_channel_id} 已被其他摄像头使用")
        
        # 处理帧率验证
        if camera_data.processing_fps is not None:
            if camera_data.processing_fps < 1 or camera_data.processing_fps > 30:
                errors.append("处理帧率必须在1-30之间")
        
        # 优先级验证
        if camera_data.priority_level is not None:
            if camera_data.priority_level < 1 or camera_data.priority_level > 10:
                errors.append("优先级必须在1-10之间")
        
        if errors:
            raise CameraValidationError(f"更新数据验证失败: {'; '.join(errors)}")
    
    @crud_error_handler("delete_camera")
    def delete_camera(self, camera_id: int, force: bool = False) -> bool:
        """
        删除摄像头 - 包含依赖关系检查
        
        Args:
            camera_id: 摄像头ID
            force: 是否强制删除
            
        Returns:
            bool: 删除是否成功
            
        Raises:
            CameraNotFoundError: 摄像头不存在
            CameraBusinessError: 存在依赖关系
        """
        try:
            # 1. 使用增强验证器验证删除操作
            validation_summary = self.validator.validate_delete(camera_id)
            
            # 2. 检查验证结果
            if not validation_summary.valid and not force:
                error_messages = ValidationHelper.format_validation_messages(validation_summary)
                raise CameraBusinessError(f"摄像头删除验证失败:\n" + "\n".join(error_messages))
            
            # 3. 记录验证警告（如果有）
            if validation_summary.warnings:
                warning_messages = [f"[WARNING] {w.field}: {w.message}" for w in validation_summary.warnings]
                logger.warning("摄像头删除验证警告", 
                             camera_id=camera_id, 
                             warnings=warning_messages)
            
            # 4. 使用增强仓储的删除方法，包含依赖检查
            result = self.enhanced_repository.delete_with_dependency_check(camera_id, force)
            
            if result:
                logger.info("摄像头删除成功", camera_id=camera_id, force=force)
            
            return result
            
        except (CameraRepositoryError, CRUDError) as e:
            logger.error("摄像头删除失败", camera_id=camera_id, error=str(e))
            raise CameraBusinessError(f"删除摄像头失败: {str(e)}") from e
        except Exception as e:
            logger.error("摄像头删除异常", camera_id=camera_id, error=str(e))
            raise CameraServiceError(f"删除摄像头异常: {str(e)}") from e
    
    async def test_camera_connection(self, camera_id: int) -> CameraConnectionTest:
        """测试摄像头连接"""
        camera = self.repository.get_by_id(camera_id)
        if not camera:
            return CameraConnectionTest(
                success=False,
                message="摄像头不存在",
                error_code="CAMERA_NOT_FOUND"
            )
        
        return await self.test_rtsp_connection(camera.rtsp_url)
    
    async def test_rtsp_connection(self, rtsp_url: str) -> CameraConnectionTest:
        """测试RTSP连接"""
        try:
            import time
            start_time = time.time()
            
            # 这里使用简单的HTTP HEAD请求来测试连接
            # 在实际项目中，应该使用专门的RTSP客户端库
            timeout = httpx.Timeout(5.0)
            async with httpx.AsyncClient(timeout=timeout) as client:
                try:
                    # 尝试解析RTSP URL并转换为HTTP测试
                    if rtsp_url.startswith('rtsp://'):
                        # 简单的连接测试，实际应该使用RTSP协议
                        response_time = time.time() - start_time
                        
                        # 模拟连接测试结果
                        if "192.168.1" in rtsp_url:  # 模拟内网地址可连接
                            return CameraConnectionTest(
                                success=True,
                                message="连接成功",
                                response_time=response_time
                            )
                        else:
                            return CameraConnectionTest(
                                success=False,
                                message="无法连接到RTSP流",
                                response_time=response_time,
                                error_code="CONNECTION_FAILED"
                            )
                    else:
                        return CameraConnectionTest(
                            success=False,
                            message="无效的RTSP地址格式",
                            error_code="INVALID_URL"
                        )
                        
                except Exception as e:
                    response_time = time.time() - start_time
                    return CameraConnectionTest(
                        success=False,
                        message=f"连接测试失败: {str(e)}",
                        response_time=response_time,
                        error_code="CONNECTION_ERROR"
                    )
                    
        except Exception as e:
            logger.error("RTSP连接测试异常", rtsp_url=rtsp_url, exc_info=e)
            return CameraConnectionTest(
                success=False,
                message=f"连接测试异常: {str(e)}",
                error_code="TEST_ERROR"
            )
    
    def update_camera_status(self, camera_id: int, status: CameraStatus) -> Optional[Camera]:
        """更新摄像头状态"""
        return self.repository.update_status(camera_id, status)
    
    def get_camera_statistics(self, detailed: bool = False) -> Dict[str, Any]:
        """
        获取摄像头统计信息
        
        Args:
            detailed: 是否返回详细统计
            
        Returns:
            Dict[str, Any]: 统计信息
        """
        try:
            if detailed:
                return self.advanced_queries.get_comprehensive_statistics(
                    include_trends=True,
                    time_range_days=30
                )
            else:
                return self.repository.get_statistics(detailed=False)
        except Exception as e:
            logger.error("获取摄像头统计信息失败", error=str(e))
            return {"error": "统计信息获取失败"}
    
    def validate_camera_name_uniqueness(self, name: str, exclude_id: int = None) -> bool:
        """
        验证摄像头名称唯一性
        
        Args:
            name: 摄像头名称
            exclude_id: 排除的摄像头ID
            
        Returns:
            bool: 名称是否唯一
        """
        try:
            return not self.repository.exists_by_name(name, exclude_id)
        except Exception as e:
            logger.error("验证摄像头名称唯一性失败", name=name, error=str(e))
            return False
    
    def search_cameras(
        self, 
        keyword: str, 
        search_fields: List[str] = None,
        limit: int = 50
    ) -> List[Camera]:
        """
        搜索摄像头
        
        Args:
            keyword: 搜索关键词
            search_fields: 搜索字段
            limit: 结果限制
            
        Returns:
            List[Camera]: 搜索结果
        """
        try:
            return self.advanced_queries.search_cameras(keyword, search_fields, limit)
        except Exception as e:
            logger.error("搜索摄像头失败", keyword=keyword, error=str(e))
            return []
    
    def get_cameras_by_location_bounds(
        self, 
        min_lng: float, 
        max_lng: float,
        min_lat: float, 
        max_lat: float,
        filters: Optional[CameraFilters] = None
    ) -> List[Camera]:
        """
        根据地理边界获取摄像头
        
        Args:
            min_lng: 最小经度
            max_lng: 最大经度
            min_lat: 最小纬度
            max_lat: 最大纬度
            filters: 额外筛选条件
            
        Returns:
            List[Camera]: 摄像头列表
        """
        try:
            bounds = LocationBounds(min_lng, max_lng, min_lat, max_lat)
            return self.advanced_queries.get_cameras_in_bounds(bounds, filters)
        except Exception as e:
            logger.error("根据地理边界获取摄像头失败", error=str(e))
            return []
    
    def get_cameras_in_radius(
        self,
        center_lng: float,
        center_lat: float,
        radius_km: float,
        filters: Optional[CameraFilters] = None
    ) -> List[Camera]:
        """
        获取指定半径内的摄像头
        
        Args:
            center_lng: 中心经度
            center_lat: 中心纬度
            radius_km: 半径（公里）
            filters: 额外筛选条件
            
        Returns:
            List[Camera]: 摄像头列表（按距离排序）
        """
        try:
            return self.advanced_queries.get_cameras_in_radius(
                center_lng, center_lat, radius_km, filters
            )
        except Exception as e:
            logger.error("获取半径内摄像头失败", error=str(e))
            return []
    
    async def batch_update_cameras(
        self, 
        updates: List[Dict[str, Any]],
        validate_connections: bool = False
    ) -> Dict[str, Any]:
        """
        批量更新摄像头
        
        Args:
            updates: 更新列表，格式: [{"id": int, "data": dict}]
            validate_connections: 是否验证连接
            
        Returns:
            Dict[str, Any]: 批量更新结果
        """
        try:
            # 如果需要验证连接，先处理连接验证
            if validate_connections:
                for update_item in updates:
                    camera_data = update_item.get("data", {})
                    if "rtsp_url" in camera_data:
                        connection_test = await self.test_rtsp_connection(camera_data["rtsp_url"])
                        if not connection_test.success:
                            logger.warning(
                                "批量更新中RTSP连接测试失败",
                                camera_id=update_item.get("id"),
                                rtsp_url=camera_data["rtsp_url"]
                            )
            
            # 执行批量更新
            result = self.enhanced_repository.batch_update_with_validation(updates)
            
            logger.info("批量更新摄像头完成",
                       total=len(updates),
                       success=result["success_count"],
                       errors=result["error_count"])
            
            return result
            
        except Exception as e:
            logger.error("批量更新摄像头失败", error=str(e))
            return {
                "success_count": 0,
                "error_count": len(updates),
                "errors": [{"error": str(e)}],
                "updated_cameras": []
            }
    
    def get_camera_health_summary(self) -> Dict[str, Any]:
        """
        获取摄像头健康状况摘要
        
        Returns:
            Dict[str, Any]: 健康状况摘要
        """
        try:
            return self.repository.get_health_summary()
        except Exception as e:
            logger.error("获取摄像头健康摘要失败", error=str(e))
            return {"error": "健康摘要获取失败"}
    
    def get_online_cameras(self) -> List[Camera]:
        """获取在线摄像头列表"""
        return self.repository.get_online_cameras()
    
    def get_ai_enabled_cameras(self) -> List[Camera]:
        """获取启用AI分析的摄像头列表"""
        return self.repository.get_ai_enabled_cameras()
    
    async def batch_test_connections(self, camera_ids: List[int]) -> List[dict]:
        """批量测试摄像头连接"""
        results = []
        
        for camera_id in camera_ids:
            camera = self.repository.get_by_id(camera_id)
            if camera:
                test_result = await self.test_rtsp_connection(camera.rtsp_url)
                results.append({
                    "camera_id": camera_id,
                    "camera_name": camera.name,
                    "test_result": test_result
                })
                
                # 根据测试结果更新状态
                new_status = CameraStatus.ONLINE if test_result.success else CameraStatus.ERROR
                if camera.status != new_status:
                    self.repository.update_status(camera_id, new_status)
            else:
                results.append({
                    "camera_id": camera_id,
                    "camera_name": None,
                    "test_result": CameraConnectionTest(
                        success=False,
                        message="摄像头不存在",
                        error_code="CAMERA_NOT_FOUND"
                    )
                })
        
        return results
    
    def get_statistics_summary(self) -> Dict[str, Any]:
        """
        获取摄像头统计摘要信息
        
        Returns:
            Dict[str, Any]: 统计摘要信息
        """
        try:
            # 使用统计服务获取摘要信息
            return self.statistics_service.get_summary_statistics()
        except Exception as e:
            logger.error("获取摄像头统计摘要失败", error=str(e))
            return {
                "total_cameras": 0,
                "online_cameras": 0,
                "offline_cameras": 0,
                "ai_enabled_cameras": 0,
                "error": "统计摘要获取失败"
            }
    
    async def refresh_all_camera_status(self) -> dict:
        """刷新所有摄像头状态"""
        cameras = self.repository.get_list(CameraFilters(size=1000))[0]  # 获取所有摄像头
        camera_ids = [camera.id for camera in cameras]
        
        results = await self.batch_test_connections(camera_ids)
        
        # 统计结果
        total = len(results)
        online = sum(1 for r in results if r["test_result"].success)
        offline = total - online
        
        return {
            "total_tested": total,
            "online": online,
            "offline": offline,
            "success_rate": round(online / total * 100, 2) if total > 0 else 0
        }
    
    async def update_camera_ai_config(self, camera_id: int, ai_config: Dict[str, Any], user_id: Optional[str] = None) -> bool:
        """更新摄像头AI算法配置"""
        try:
            # 验证摄像头是否存在
            camera = self.repository.get_by_id(camera_id)
            if not camera:
                logger.warning("摄像头不存在", camera_id=camera_id)
                return False
            
            # 创建AI配置对象
            config = CameraAIConfig(
                camera_id=str(camera_id),
                enabled_algorithms=ai_config.get("enabled_algorithms", []),
                processing_fps=ai_config.get("processing_fps", 3),
                priority_level=ai_config.get("priority_level", 5),
                custom_settings=ai_config.get("custom_settings", {})
            )
            
            # 更新配置
            success = await self.config_manager.update_camera_ai_config(str(camera_id), config, user_id)
            
            if success:
                # 更新数据库中的AI算法配置
                update_data = CameraUpdate(ai_algorithms=ai_config.get("enabled_algorithms", []))
                self.repository.update(camera_id, update_data)
                
                logger.info("摄像头AI配置更新成功", camera_id=camera_id, algorithms=config.enabled_algorithms)
            
            return success
            
        except Exception as e:
            logger.error("摄像头AI配置更新失败", camera_id=camera_id, error=str(e))
            return False
    
    def get_camera_ai_config(self, camera_id: int) -> Optional[Dict[str, Any]]:
        """获取摄像头AI算法配置"""
        try:
            config = self.config_manager.get_camera_ai_config(str(camera_id))
            if config:
                return {
                    "camera_id": camera_id,
                    "enabled_algorithms": config.enabled_algorithms,
                    "processing_fps": config.processing_fps,
                    "priority_level": config.priority_level,
                    "custom_settings": config.custom_settings
                }
            
            # 如果没有配置，返回默认配置
            from core.config import get_settings
            settings = get_settings()
            return {
                "camera_id": camera_id,
                "enabled_algorithms": settings.DEFAULT_AI_ALGORITHMS,
                "processing_fps": settings.VIDEO_PROCESSING_FPS,
                "priority_level": 5,
                "custom_settings": {}
            }
            
        except Exception as e:
            logger.error("获取AI配置失败", exc_info=e)
            return {
                "enabled": False,
                "algorithms": [],
                "confidence_threshold": 0.5,
                "processing_fps": 1.0,
                "priority_level": 1,
                "custom_settings": {}
            }
    
    def validate_camera_data(self, camera_data: CameraCreate) -> Dict[str, Any]:
        """
        验证摄像头数据并返回详细的验证结果
        
        Args:
            camera_data: 摄像头数据
            
        Returns:
            Dict[str, Any]: 验证结果详情
        """
        try:
            validation_summary = self.validator.validate_create(camera_data)
            
            return {
                "valid": validation_summary.valid,
                "summary": validation_summary.get_summary_dict(),
                "results": [result.to_dict() for result in validation_summary.results],
                "messages": ValidationHelper.format_validation_messages(validation_summary),
                "summary_text": ValidationHelper.get_validation_summary_text(validation_summary)
            }
            
        except Exception as e:
            logger.error("验证摄像头数据失败", error=str(e))
            return {
                "valid": False,
                "summary": {"error": "验证过程发生异常"},
                "results": [],
                "messages": [f"验证异常: {str(e)}"],
                "summary_text": "验证失败"
            }
    
    def validate_camera_update_data(self, camera_id: int, camera_data: CameraUpdate) -> Dict[str, Any]:
        """
        验证摄像头更新数据并返回详细的验证结果
        
        Args:
            camera_id: 摄像头ID
            camera_data: 更新数据
            
        Returns:
            Dict[str, Any]: 验证结果详情
        """
        try:
            validation_summary = self.validator.validate_update(camera_id, camera_data)
            
            return {
                "valid": validation_summary.valid,
                "summary": validation_summary.get_summary_dict(),
                "results": [result.to_dict() for result in validation_summary.results],
                "messages": ValidationHelper.format_validation_messages(validation_summary),
                "summary_text": ValidationHelper.get_validation_summary_text(validation_summary)
            }
            
        except Exception as e:
            logger.error("验证摄像头更新数据失败", camera_id=camera_id, error=str(e))
            return {
                "valid": False,
                "summary": {"error": "验证过程发生异常"},
                "results": [],
                "messages": [f"验证异常: {str(e)}"],
                "summary_text": "验证失败"
            }
            logger.error("获取摄像头AI配置失败", camera_id=camera_id, error=str(e))
            return None
    
    async def batch_update_ai_configs(self, configs: Dict[int, Dict[str, Any]], user_id: Optional[str] = None) -> Dict[int, bool]:
        """批量更新摄像头AI配置"""
        results = {}
        
        for camera_id, ai_config in configs.items():
            results[camera_id] = await self.update_camera_ai_config(camera_id, ai_config, user_id)
        
        return results
    
    def get_cameras_by_algorithm(self, algorithm_name: str) -> List[Camera]:
        """获取启用指定AI算法的摄像头列表"""
        try:
            all_configs = self.config_manager.get_all_camera_ai_configs()
            camera_ids = []
            
            for camera_id_str, config in all_configs.items():
                if algorithm_name in config.enabled_algorithms:
                    camera_ids.append(int(camera_id_str))
            
            cameras = []
            for camera_id in camera_ids:
                camera = self.repository.get_by_id(camera_id)
                if camera:
                    cameras.append(camera)
            
            return cameras
            
        except Exception as e:
            logger.error("获取算法摄像头列表失败", algorithm=algorithm_name, error=str(e))
            return []
    
    def get_ai_algorithm_statistics(self) -> Dict[str, Any]:
        """获取AI算法使用统计"""
        try:
            all_configs = self.config_manager.get_all_camera_ai_configs()
            algorithm_stats = {}
            total_cameras = len(all_configs)
            
            # 统计每个算法的使用情况
            for config in all_configs.values():
                for algorithm in config.enabled_algorithms:
                    if algorithm not in algorithm_stats:
                        algorithm_stats[algorithm] = 0
                    algorithm_stats[algorithm] += 1
            
            # 计算使用率
            algorithm_usage = {}
            for algorithm, count in algorithm_stats.items():
                algorithm_usage[algorithm] = {
                    "camera_count": count,
                    "usage_rate": round(count / total_cameras * 100, 2) if total_cameras > 0 else 0
                }
            
            return {
                "total_cameras_with_ai": total_cameras,
                "algorithm_usage": algorithm_usage,
                "most_used_algorithm": max(algorithm_stats.items(), key=lambda x: x[1])[0] if algorithm_stats else None
            }
            
        except Exception as e:
            logger.error("获取AI算法统计失败", error=str(e))
            return {}
    
    async def validate_ai_config(self, camera_id: int, ai_config: Dict[str, Any]) -> Dict[str, Any]:
        """验证AI配置"""
        validation_result = {
            "valid": True,
            "errors": [],
            "warnings": []
        }
        
        try:
            # 验证摄像头是否存在
            camera = self.repository.get_by_id(camera_id)
            if not camera:
                validation_result["valid"] = False
                validation_result["errors"].append("摄像头不存在")
                return validation_result
            
            # 验证算法列表
            enabled_algorithms = ai_config.get("enabled_algorithms", [])
            available_algorithms = [
                "behavior_analysis", "crowd_density", "waste_detection",
                "cleanliness_assessment", "teaching_quality", "classroom_quality",
                "conflict_detection", "pose_detection", "trajectory_analysis",
                "lighting_detection", "energy_analysis"
            ]
            
            for algorithm in enabled_algorithms:
                if algorithm not in available_algorithms:
                    validation_result["valid"] = False
                    validation_result["errors"].append(f"未知的AI算法: {algorithm}")
            
            # 验证处理帧率
            processing_fps = ai_config.get("processing_fps", 3)
            if not isinstance(processing_fps, int) or not (1 <= processing_fps <= 30):
                validation_result["valid"] = False
                validation_result["errors"].append("处理帧率必须在1-30之间")
            
            # 验证优先级
            priority_level = ai_config.get("priority_level", 5)
            if not isinstance(priority_level, int) or not (1 <= priority_level <= 10):
                validation_result["valid"] = False
                validation_result["errors"].append("优先级必须在1-10之间")
            
            # 性能警告
            if len(enabled_algorithms) > 5:
                validation_result["warnings"].append("启用过多AI算法可能影响性能")
            
            if processing_fps > 10:
                validation_result["warnings"].append("高帧率处理可能消耗大量资源")
            
        except Exception as e:
            validation_result["valid"] = False
            validation_result["errors"].append(f"验证过程出错: {str(e)}")
        
        return validation_result

    async def validate_camera_business_rules(
        self, 
        camera_data: CameraCreate,
        exclude_id: int = None
    ) -> Dict[str, Any]:
        """
        验证摄像头业务规则
        
        Args:
            camera_data: 摄像头数据
            exclude_id: 排除的摄像头ID（用于更新时）
            
        Returns:
            Dict[str, Any]: 验证结果
        """
        validation_result = {
            "valid": True,
            "errors": [],
            "warnings": []
        }
        
        try:
            # 名称唯一性检查
            if not self.validate_camera_name_uniqueness(camera_data.name, exclude_id):
                validation_result["valid"] = False
                validation_result["errors"].append(f"摄像头名称 '{camera_data.name}' 已存在")
            
            # WVP设备唯一性检查
            if camera_data.wvp_device_id and camera_data.wvp_channel_id:
                existing_wvp = self.repository.get_by_wvp_device(
                    camera_data.wvp_device_id, 
                    camera_data.wvp_channel_id
                )
                if existing_wvp and (exclude_id is None or existing_wvp.id != exclude_id):
                    validation_result["valid"] = False
                    validation_result["errors"].append(
                        f"WVP设备 {camera_data.wvp_device_id}:{camera_data.wvp_channel_id} 已存在"
                    )
            
            # 位置摄像头数量检查
            if camera_data.location:
                location_cameras = self.repository.get_cameras_by_location(
                    camera_data.location, exact_match=True
                )
                if exclude_id:
                    location_cameras = [c for c in location_cameras if c.id != exclude_id]
                
                if len(location_cameras) >= self.max_cameras_per_location:
                    validation_result["warnings"].append(
                        f"位置 '{camera_data.location}' 的摄像头数量接近上限"
                    )
            
            # 距离检查
            nearby_cameras = self.get_cameras_in_radius(
                camera_data.longitude,
                camera_data.latitude,
                self.min_camera_distance_meters / 1000
            )
            if exclude_id:
                nearby_cameras = [c for c in nearby_cameras if c.id != exclude_id]
            
            if nearby_cameras:
                validation_result["warnings"].append(
                    f"附近{self.min_camera_distance_meters}米内有其他摄像头"
                )
            
        except Exception as e:
            validation_result["valid"] = False
            validation_result["errors"].append(f"验证过程出错: {str(e)}")
        
        return validation_result
    
    def get_comprehensive_statistics(
        self, 
        include_trends: bool = True,
        time_range_days: int = 30
    ) -> Dict[str, Any]:
        """
        获取综合统计信息 - 集成统计监控服务
        
        Args:
            include_trends: 是否包含趋势数据
            time_range_days: 时间范围（天）
            
        Returns:
            Dict[str, Any]: 综合统计信息
        """
        try:
            return self.statistics_service.get_comprehensive_statistics(
                include_trends=include_trends,
                time_range_days=time_range_days
            )
        except Exception as e:
            logger.error("获取综合统计信息失败", error=str(e))
            return {"error": "综合统计信息获取失败", "message": str(e)}
    
    def perform_system_health_check(self) -> Dict[str, Any]:
        """
        执行系统健康检查
        
        Returns:
            Dict[str, Any]: 健康检查结果
        """
        try:
            health_results = self.statistics_service.perform_health_check()
            
            # 格式化健康检查结果
            formatted_results = []
            health_summary = {"healthy": 0, "warning": 0, "critical": 0}
            
            for result in health_results:
                formatted_results.append({
                    "check_name": result.check_name,
                    "status": result.status,
                    "message": result.message,
                    "timestamp": result.timestamp.isoformat(),
                    "details": result.details
                })
                health_summary[result.status] += 1
            
            # 计算整体健康分数
            total_checks = len(health_results)
            health_score = 0
            if total_checks > 0:
                health_score = (
                    health_summary["healthy"] * 100 +
                    health_summary["warning"] * 50 +
                    health_summary["critical"] * 0
                ) / total_checks
            
            return {
                "health_checks": formatted_results,
                "summary": health_summary,
                "overall_health_score": round(health_score, 2),
                "total_checks": total_checks,
                "check_timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error("系统健康检查失败", error=str(e))
            return {
                "error": "健康检查失败",
                "message": str(e),
                "check_timestamp": datetime.now().isoformat()
            }
    
    def check_data_consistency(self) -> Dict[str, Any]:
        """
        执行数据一致性检查
        
        Returns:
            Dict[str, Any]: 数据一致性检查结果
        """
        try:
            consistency_report = self.statistics_service.check_data_consistency()
            
            return {
                "total_cameras": consistency_report.total_cameras,
                "total_issues": len(consistency_report.inconsistencies),
                "severity_counts": consistency_report.severity_counts,
                "issues": consistency_report.inconsistencies,
                "check_timestamp": consistency_report.check_timestamp.isoformat(),
                "status": "healthy" if len(consistency_report.inconsistencies) == 0 else 
                         "warning" if consistency_report.severity_counts.get("critical", 0) == 0 else 
                         "critical"
            }
            
        except Exception as e:
            logger.error("数据一致性检查失败", error=str(e))
            return {
                "error": "数据一致性检查失败",
                "message": str(e),
                "check_timestamp": datetime.now().isoformat()
            }
    
    def get_performance_metrics(self, hours: int = 1) -> Dict[str, Any]:
        """
        获取性能指标
        
        Args:
            hours: 时间范围（小时）
            
        Returns:
            Dict[str, Any]: 性能指标
        """
        try:
            # 获取最近指定小时的性能指标
            recent_metrics = [
                metric for metric in self.statistics_service.performance_metrics
                if metric.timestamp >= datetime.now() - timedelta(hours=hours)
            ]
            
            if not recent_metrics:
                return {
                    "message": f"最近{hours}小时内无性能数据",
                    "time_range_hours": hours,
                    "metrics_count": 0
                }
            
            # 按操作类型分组统计
            operation_stats = {}
            for metric in recent_metrics:
                if metric.operation_name not in operation_stats:
                    operation_stats[metric.operation_name] = {
                        "count": 0,
                        "total_time": 0,
                        "success_count": 0,
                        "error_count": 0,
                        "min_time": float('inf'),
                        "max_time": 0,
                        "errors": []
                    }
                
                stats = operation_stats[metric.operation_name]
                stats["count"] += 1
                stats["total_time"] += metric.execution_time
                stats["min_time"] = min(stats["min_time"], metric.execution_time)
                stats["max_time"] = max(stats["max_time"], metric.execution_time)
                
                if metric.success:
                    stats["success_count"] += 1
                else:
                    stats["error_count"] += 1
                    if metric.error_message:
                        stats["errors"].append(metric.error_message)
            
            # 计算平均值和成功率
            for operation, stats in operation_stats.items():
                stats["avg_time"] = round(stats["total_time"] / stats["count"], 4)
                stats["success_rate"] = round(stats["success_count"] / stats["count"] * 100, 2)
                stats["min_time"] = round(stats["min_time"], 4)
                stats["max_time"] = round(stats["max_time"], 4)
                del stats["total_time"]  # 移除中间计算值
            
            # 整体统计
            overall_success_rate = sum(1 for m in recent_metrics if m.success) / len(recent_metrics) * 100
            avg_response_time = sum(m.execution_time for m in recent_metrics) / len(recent_metrics)
            
            return {
                "time_range_hours": hours,
                "total_operations": len(recent_metrics),
                "operation_statistics": operation_stats,
                "overall_success_rate": round(overall_success_rate, 2),
                "average_response_time": round(avg_response_time, 4),
                "generated_at": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error("获取性能指标失败", error=str(e))
            return {"error": "性能指标获取失败", "message": str(e)}
    
    def get_camera_status_management(self) -> Dict[str, Any]:
        """
        获取摄像头状态管理信息
        
        Returns:
            Dict[str, Any]: 状态管理信息
        """
        try:
            # 获取状态分布
            status_distribution = self.statistics_service._get_status_distribution()
            
            # 获取在线摄像头
            online_cameras = self.get_online_cameras()
            
            # 获取AI启用摄像头
            ai_cameras = self.get_ai_enabled_cameras()
            
            # 计算状态统计
            total_cameras = self.db.query(func.count(Camera.id)).scalar()
            online_count = len(online_cameras)
            ai_count = len(ai_cameras)
            
            # 最近状态变化（模拟数据，实际需要状态变更日志）
            recent_status_changes = self._get_recent_status_changes()
            
            return {
                "status_distribution": status_distribution,
                "summary": {
                    "total_cameras": total_cameras,
                    "online_cameras": online_count,
                    "ai_enabled_cameras": ai_count,
                    "online_ratio": round(online_count / total_cameras * 100, 2) if total_cameras > 0 else 0,
                    "ai_ratio": round(ai_count / total_cameras * 100, 2) if total_cameras > 0 else 0
                },
                "recent_changes": recent_status_changes,
                "generated_at": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error("获取摄像头状态管理信息失败", error=str(e))
            return {"error": "状态管理信息获取失败", "message": str(e)}
    
    def _get_recent_status_changes(self) -> List[Dict[str, Any]]:
        """获取最近状态变化（模拟实现）"""
        # 实际实现需要状态变更日志表
        try:
            # 获取最近更新的摄像头作为状态变化的模拟
            recent_updates = (
                self.db.query(Camera.id, Camera.name, Camera.status, Camera.updated_at)
                .filter(Camera.updated_at >= datetime.now() - timedelta(hours=24))
                .order_by(Camera.updated_at.desc())
                .limit(20)
                .all()
            )
            
            return [
                {
                    "camera_id": camera.id,
                    "camera_name": camera.name,
                    "current_status": camera.status.value,
                    "change_time": camera.updated_at.isoformat(),
                    "change_type": "status_update"  # 模拟变更类型
                }
                for camera in recent_updates
            ]
        except Exception as e:
            logger.error("获取最近状态变化失败", error=str(e))
            return []
    
    def get_service_statistics(self) -> Dict[str, Any]:
        """
        获取服务统计信息
        
        Returns:
            Dict[str, Any]: 服务统计信息
        """
        try:
            return {
                "service_name": "CameraService",
                "version": "1.0.0",
                "features": [
                    "create_camera_with_validation",
                    "update_camera_with_validation", 
                    "delete_camera_with_dependency_check",
                    "advanced_queries",
                    "batch_operations",
                    "connection_testing",
                    "business_rule_validation",
                    "comprehensive_statistics",
                    "health_monitoring",
                    "data_consistency_checking",
                    "performance_tracking"
                ],
                "repository_type": "EnhancedCameraRepository",
                "advanced_queries_enabled": True,
                "statistics_service_enabled": True,
                "monitoring_features": {
                    "health_checks": True,
                    "performance_metrics": True,
                    "data_consistency": True,
                    "status_management": True
                },
                "business_rules": {
                    "max_cameras_per_location": self.max_cameras_per_location,
                    "min_camera_distance_meters": self.min_camera_distance_meters,
                    "allowed_rtsp_ports": self.allowed_rtsp_ports,
                    "coordinate_precision": self.coordinate_precision
                }
            }
        except Exception as e:
            logger.error("获取服务统计信息失败", error=str(e))
            return {"error": "服务统计信息获取失败"}


# 全局摄像头服务实例 - 延迟初始化
_camera_service_instance = None

def get_camera_service(db: Session = None) -> Optional[CameraService]:
    """
    获取摄像头服务实例
    
    Args:
        db: 数据库会话
        
    Returns:
        Optional[CameraService]: 摄像头服务实例
    """
    global _camera_service_instance
    
    if db is not None:
        # 每次都创建新实例以确保使用正确的数据库会话
        return CameraService(db)
    
    return _camera_service_instance

def create_camera_service(db: Session) -> CameraService:
    """
    创建摄像头服务实例
    
    Args:
        db: 数据库会话
        
    Returns:
        CameraService: 摄像头服务实例
    """
    return CameraService(db)
# 创建默认的摄像头服务实例
camera_service = None  # 将在应用启动时初始化